import * as fs from 'fs';
import * as path from 'path';
import {
  app,
  BrowserWindow,
  Menu,
  MenuItemConstructorOptions,
  ipcMain,
  Tray,
} from 'electron';
import { setTab, importFile, openDevTools, exportFile } from './menuClick';
import { Server } from './server';

const menu: MenuItemConstructorOptions[] = [
  {
    label: '文件(&F)',
    submenu: [
      { label: '导入', click: importFile },
      {
        label: '导出为...',
        submenu: [
          { label: 'json格式', click(_menuItem, browserWindow) { exportFile(browserWindow, 'json') } },
          { label: 'km格式', click(_menuItem, browserWindow) { exportFile(browserWindow, 'km') } },
          { label: 'txt格式', click(_menuItem, browserWindow) { exportFile(browserWindow, 'txt') } },
          { label: 'markdown格式', click(_menuItem, browserWindow) { exportFile(browserWindow, 'md') } },
          { label: 'svg矢量格式', click(_menuItem, browserWindow) { exportFile(browserWindow, 'svg') } },
          { label: 'png位图格式', click(_menuItem, browserWindow) { exportFile(browserWindow, 'png') } },
        ],
      },
      { type: 'separator' },
      { label: '关闭', role: 'close' },
    ],
  },
  {
    label: '视图(&V)',
    submenu: [
      {
        label: '思路',
        type: 'checkbox',
        accelerator: 'Ctrl+1',
        checked: true,
        click(menuItem, browserWindow) { setTab(menuItem, browserWindow, '思路'); },
      },
      {
        label: '外观',
        type: 'checkbox',
        accelerator: 'Ctrl+2',
        checked: false,
        click(menuItem, browserWindow) { setTab(menuItem, browserWindow, '外观'); },
      },
      {
        label: '操作',
        type: 'checkbox',
        accelerator: 'Ctrl+3',
        checked: false,
        click(menuItem, browserWindow) { setTab(menuItem, browserWindow, '操作'); },
      },
      { type: 'separator' },
      { label: '切换全屏', accelerator: 'F11', role: 'togglefullscreen' },
      { type: 'separator' },
      {
        label: '实际大小',
        accelerator: 'Ctrl+Shift+9',
        role: 'resetZoom',
      },
      {
        label: '放大',
        accelerator: 'Ctrl+Shift+=',
        role: 'zoomIn',
      },
      {
        label: '缩小',
        accelerator: 'Ctrl+Shift+-',
        role: 'zoomOut',
      },
      { type: 'separator' },
      {
        label: '开发者工具',
        accelerator: 'F12',
        click: openDevTools,
      },
    ],
  },
  // {
  //   label: '帮助(&H)',
  //   submenu: [
  //     { label: '更新日志' },
  //     { label: '赞助' },
  //     { label: '反馈' },
  //     { type: 'separator' },
  //     { label: '检查更新...' },
  //     { label: '关于' },
  //   ],
  // },
];

const server = new Server('http://49.232.15.194:1169/api/mind-server');

async function createWindow() {
  Menu.setApplicationMenu(Menu.buildFromTemplate(menu));
  // 文件导出
  ipcMain.on('saveFile', (event, { filePath, data, type }) => {
    if (type === 'png') {
      data = new Buffer(data.replace(/^data:image\/\w+;base64,/, ''), 'base64')
    }
    fs.writeFile(filePath, data, (err) => {
      event.sender.send('showMessage', {
        leval: err ? 'error' : 'success',
        message: `文件导出${ err ? '失败' : '成功' }`,
      });
      if (err) {
        event.sender.send('console', err);
      }
    });
  });

  // 检测文件变动
  ipcMain.on('contentChange', async (event, { fileId, data }) => {
    try {
      const result = await server.updateFileData(fileId, data);
      if (result.success) {
        event.sender.send('showMessage', {
          leval: 'success',
          message: '文件上传成功!',
        });
      } else {
        event.sender.send('showMessage', {
          leval: 'error',
          message: result.message,
        });
      }
    } catch (error) {
      event.sender.send('showMessage', {
        leval: 'error',
        message: error,
      });
    }
  });

  // 登录
  ipcMain.on('login', async (event, { url, username, password }) => {
    server.url = url;
    const result = await server.login(username, password);
    event.sender.send('loginResult', {
      success: result.success,
      message: result.message,
      password: result.password,
      nickname: result.user?.nickname,
      headImage: result.user?.headImage,
    });
  });

  // 登陆成功跳转
  ipcMain.on('toExplor', async (_event, { headImage, nickname, viewId }) => {
    await initExplorer(nickname, headImage);
    BrowserWindow.fromId(viewId).destroy();
  });

  // 创建文件
  ipcMain.on('createFile', async (event, { name, explorId }) => {
    const result = await server.createFile(name, '');
    const view = await initEdit(result.fileId, name, '', explorId);
    event.sender.send('subViewId', { fileId: result.fileId, viewId: view.id });
    event.sender.send('createFileResult', { success: true });
  });

  // 重命名文件
  ipcMain.on('renameFile', async (event, { fileId, newName, viewId }) => {
    const result = await server.renameFile(fileId, newName);
    event.sender.send('renameFileResult', result);
    const view = getView(viewId);
    if (view) {
      view.setTitle(newName);
    }
  });

  // 获取文件列表
  ipcMain.on('getFile', async (event) => {
    const result = await server.getFileList();
    event.sender.send('getFileResult', result);
  });

  // 获取回收站文件
  ipcMain.on('getRecycle', async (event) => {
    const result = await server.getRecycleList();
    event.sender.send('getRecycleResult', result);
  });

  // 回收文件
  ipcMain.on('recycleFile', async (event, fileId) => {
    const result = await server.recycleFile(fileId);
    event.sender.send('recycleFileResult', result);
  });

  // 恢复文件
  ipcMain.on('revertFile', async (event, fileId) => {
    const result = await server.revertFile(fileId);
    event.sender.send('revertFileResult', result);
  });

  // 删除文件
  ipcMain.on('deleteFile', async (event, fileId) => {
    const result = await server.deleteFile(fileId);
    event.sender.send('deleteFileResult', result);
  });

  // 清空回收站
  ipcMain.on('clearRecycle', async (event) => {
    const result = await server.clearRecycle();
    event.sender.send('clearRecycleResult', result);
  });

  // 跳转编辑器
  ipcMain.on('toEdit', async (event, { fileId, viewId, explorId }) => {
    let view = getView(viewId);
    if (view) {
      view.focus();
      return;
    }
    const result = await server.getFileData(fileId);
    if (!result.success) {
      event.sender.send('showMessage', {
        leval: 'error',
        message: result.message,
      });
      return;
    }
    view = await initEdit(fileId, result.file.name, result.file.data, explorId);
    event.sender.send('subViewId', { fileId, viewId: view.id });
  });

  ipcMain.on('logout', async (event) => {
    const result = await server.logout();
    if (!result.success) {
      event.sender.send('showMessage', {
        leval: 'error',
        message: result.message,
      });
      return;
    }
  });

  ipcMain.on('minimize', (_event, id) => {
    BrowserWindow.fromId(id).minimize();
  });

  ipcMain.on('maximize', (_event, id) => {
    BrowserWindow.fromId(id).maximize();
  });

  ipcMain.on('unmaximize', (_event, id) => {
    BrowserWindow.fromId(id).unmaximize();
  });

  ipcMain.on('close', (_event, id) => {
    BrowserWindow.fromId(id).destroy();
  });

  ipcMain.on('hide', (_event, id) => {
    BrowserWindow.fromId(id).hide();
  });

  await initLoginView();
}

async function initLoginView() {
  // 创建浏览器窗口
  const view = new BrowserWindow({
    webPreferences: { nodeIntegration: true },
    // 是否显示边框
    frame: false,
    // 是否可以改变大小
    resizable: false,
    // 开启在任务栏中不显示
    skipTaskbar: false,
    width: 600,
    height: 400,
  });
  await view.loadFile(path.join(__dirname, '../view/login.html'));
  view.webContents.send('viewId', view.id);
}

async function initExplorer(nickname: string, headImage: string) {
  // 创建浏览器窗口
  const view = new BrowserWindow({
    webPreferences: { nodeIntegration: true },
    // 是否显示边框
    frame: false,
    // 是否可以改变大小
    resizable: false,
    // 开启在任务栏中不显示
    skipTaskbar: true,
    width: 1000,
    height: 600,
  });
  await view.loadFile(path.join(__dirname, '../view/index.html'));
  view.webContents.send('init', { nickname, headImage, viewId: view.id });
  view.on('maximize', () => {
    view.webContents.send('changeMaximize', true);
  });
  view.on('unmaximize', () => {
    view.webContents.send('changeMaximize', false);
  });
  const tray = new Tray(path.join(__dirname, '../view/img/logo.png'));
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '退出',
      click: () => {
        view.destroy();
      },
    },
  ]);
  tray.setToolTip('天命图');
  tray.setContextMenu(contextMenu)
  tray.on('click', () => {
    view.show();
  });
}

async function initEdit(fileId: string, name: string, data: string, explorId: number) {
  // 创建浏览器窗口
  const view = new BrowserWindow({
    webPreferences: { nodeIntegration: true },
    // 是否显示边框
    frame: true,
    // 是否可以改变大小
    resizable: true,
    // 开启在任务栏中不显示
    skipTaskbar: false,
    minWidth: 1200,
    minHeight: 800,
    title: name,
  });
  await view.loadFile(path.join(__dirname, '../view/kityminder/index.html'));
  view.fileName = name;
  view.webContents.send('init', {
    data,
    name,
    fileId,
    viewId: view.id,
  });
  view.on('closed', () => {
    const explorView = getView(explorId);
    if (explorView) {
      explorView.webContents.send('editClose', fileId);
    }
  });
  return view;
}
function getView(viewId: number) {
  try {
    return BrowserWindow.fromId(viewId);
  } catch (error) {
    return null;
  }
}

async function init() {
  await app.whenReady();
  await createWindow();
}

init();
